<template>
  <div class="all" v-if="curData">
    <!-- 价格提醒 -->
    <scroller class="scroller" ref="scroller" resize="none">

      <div class="wrapper">
        <!-- 标的 -->
        <text class="font28 text3 mb20">{{T('标的')}}</text>
        <div class="search bg2 mb30" @click="searchClick">
          <LImage v-if="pageRef != 'edit'" class="search-image mr20" :src="Config.img('ic_ai_search.png')"></LImage>
          <text :class="['font30', pair.length > 0 ? 'text2' : 'text3']">{{ pair.length > 0 ? pair :T('请选择标的')}}</text>
        </div>
        <!-- 当前价格 -->
        <div class="price-bg mb30">
          <LImage class="price-bg-img" :src="Config.img('ic_ai_price_bg.png')"></LImage>
          <LImage class="price-left-img" :src="Config.img('ic_ai_price.png')"></LImage>
          <text class="font30 text1 ml8">{{T('当前价格')}}</text>
          <div class="all acenter">
            <text class="font46 text1 fontz">{{ curPriceData ?  curPriceData.last : '---'}}</text>
            <text class="font30 text5">{{ curPriceData ?  '≈$'+curPriceData.usdPrice : '≈$ ---'}}</text>
          </div>
        </div>
        <!-- 价格选择 -->
        <div v-if="curPriceData" class="row mb30">
          <div class="price-sel-bg" @click="onPriceSel">
            <text class="font24 text2 mr20">{{ T(curPriceCondition.operatorName) }}</text>
            <LImage class="cell-arrow" :src="Config.img('jiantou_lan.png')" />
          </div>
        </div>

        <VPriceUp ref="priceUp" v-if="curPriceData && curPriceCondition.operator == 'up'" class="acenter mb40"
          :condition="curPriceCondition" :dPrice="curPriceData.last" @onPriceChange="onPriceChange" />

        <VPriceDown ref="priceDown" v-if="curPriceData && curPriceCondition.operator == 'down'" class="acenter mb40"
          :condition="curPriceCondition" :dPrice="curPriceData.last" @onPriceChange="onPriceChange" />

        <VPriceEnter ref="priceEnter" v-if="curPriceData && curPriceCondition.operator == 'enteringChannel'"
          class="acenter mb40" :condition="curPriceCondition" :dPrice="curPriceData.last"
          @onPriceChangeValue1="onPriceChangeValue1" @onPriceChangeValue2="onPriceChangeValue2" />

        <VPriceExit ref="priceExit" v-if="curPriceData && curPriceCondition.operator == 'exitingChannel'"
          class="acenter mb40" :condition="curPriceCondition" :dPrice="curPriceData.last"
          @onPriceChangeValue1="onPriceChangeValue1" @onPriceChangeValue2="onPriceChangeValue2" />

        <!-- 频率 -->
        <text class="font28 text3 mb20">{{T('频率')}}</text>
        <VConditionCell :title="frequency.name" @onConditionClick="onConditionClick" type="yjFrequency" />
        <div class="height20" />
        <!-- 到期时间 -->
        <text class="font28 text3 mb20">{{T('到期时间')}}</text>

        <VConditionCell :title="expirationTime || T('请选择到期时间')"
          :isGrayText="expirationTime && expirationTime.length > 0" @onConditionClick="onConditionClick"
          type="pickerTime" />
        <div class="height20" />
        <!-- 预警方式 -->
        <text class="font28 text3 mb20">{{T('预警方式')}}</text>
        <VCheck class="mb40" :menus="alertTypes" :selTypes="selAlertTypes" @checkClick="onAlertTypeSel" />
        <!-- 备注 -->
        <text class="font28 text3 mb20">{{T('备注')}}</text>
        <div class="bg2 textarea-bg">
          <textarea ref="note" class="textarea font30 text2 mb40" v-model="note" :placeholder="T('(选填)')"
            :maxlength="100" />

          <div class="row more-count">
            <text class="font28 text3">{{note.length+'/100'}}</text>
          </div>
        </div>

      </div>
    </scroller>

    <div class="bottom">
      <div class="but main1" @click="onSave">
        <text class="font36 text1">{{T('保存')}}</text>
      </div>
    </div>

    <x-pair type="pair" v-if="showPair" :show="showPair" @overlayClick="pairHide" @onPairClick="onPairSel" />

    <x-picker type="date" v-if="showPicker" :show="showPicker" :curDate="expirationTime || curDate"
      @overlayClick="timePickerHide" @timePickerResult="timePickerResult" />

  </div>
</template>

<style src="@/_css/style.css" ></style>
<style scoped>
  .scroller {
    display: flex;
    flex-direction: column;
    flex: 1;
  }
  .refresh {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 750px;
    height: 80px;
  }
  .wrapper {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    padding: 0 30px;
  }
  .search {
    flex-direction: row;
    align-items: center;
    height: 81px;
    padding-left: 28px;
    padding-right: 30px;
    border-color: #252a4d;
    border-radius: 4px;
    border-width: 1px;
  }
  .search-image {
    width: 32px;
    height: 32px;
  }
  .center-img {
    width: 690px;
    height: 640px;
    margin-top: 10px;
  }
  .price-bg {
    position: relative;
    flex-direction: row;
    align-items: center;
    width: 690px;
    height: 162px;
  }
  .price-bg-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 690px;
    height: 162px;
  }
  .price-left-img {
    margin-left: 40px;
    width: 34px;
    height: 38px;
  }
  .price-sel-bg {
    flex-direction: row;
    align-items: center;
    height: 56px;
    padding: 6px 24px;
    background-color: #343547;
  }
  .cell-arrow {
    width: 16px;
    height: 16px;
    transform: rotate(90deg);
  }
  .bottom {
    height: 140px;
    flex-direction: column;
    margin-bottom: 40px;
  }
  .but {
    align-items: center;
    justify-content: center;
    margin: 20px 30px;
    height: 88px;
    border-radius: 16px;
  }
  .textarea-bg {
    position: relative;
    height: 220px;
  }
  .textarea {
    padding-left: 24px;
    padding-right: 24px;
    padding-top: 30px;
    padding-bottom: 40px;
    height: 160px;
    border-radius: 4px;
    placeholder-color: #777f9b;
  }
  .more-count {
    position: absolute;
    bottom: 20px;
    right: 24px;
  }
</style>

<script>
  import XPicker from "@/aide/picker/index.vue";
  import XPair from "@/aide/pair/targetPair.vue";
  import VCheck from "@/aide/view/VCheck.vue";
  import VConditionCell from "@/aide/view/VConditionCell.vue";
  import VPriceUp from "@/aide/price/priceUp.vue";
  import VPriceDown from "@/aide/price/priceDown.vue";
  import VPriceEnter from "@/aide/price/priceEnter.vue";
  import VPriceExit from "@/aide/price/priceExit.vue";
  import dateUtils from "@/aide/picker/dateutils.js";
  import jconfig from "@/_js/config";
  import jbroadcast from "@/_js/broadcast";
  import jmodal from "@/_js/modal";
  import jdebug from "@/_js/debug";
  import jhttps from "@/_js/https";
  import jtime from "@/_js/time";
  import jnavigator from "@/_js/navigator";
  const clipboard = weex.requireModule("clipboard");
  const animation = weex.requireModule("animation"); //动画
  const domModule = weex.requireModule("dom");
  const stream = weex.requireModule("stream"); //网络请求
  const weexFunction = weex.requireModule("WeexFunction");
  import I18N from "@/_i18n/i18n";
  var T = I18N.t;

  export default {
    components: {
      XPicker,
      VCheck,
      XPair,
      VConditionCell,
      VPriceUp,
      VPriceDown,
      VPriceEnter,
      VPriceExit,
    },

    data() {
      return {
        Config: jconfig,
        T: T,
        pageRef: "", // create、edit
        id: null,
        indicatorId: null,
        type: "price",
        curData: null,
        //标的
        pair: "",
        showPair: false,
        //价格条件
        curPriceData: null, //当前价格
        priceConditionList: [], //价格条件选择
        curPriceCondition: null, //当前价格条件
        //预警频率
        frequency: {},
        frequencyList: [
          {
            name: T("仅一次"),
            type: "once",
          },
          {
            name: T("每分钟一次"),
            type: "oncePerMinute",
          },
        ],
        //到期时间
        showPicker: false,
        curDate: null,
        expirationTime: null,
        //预警方式
        alertTypes: [
          {
            name: T("APP提醒"),
            type: "app",
          },
          {
            name: T("Telegram提醒"),
            type: "tg",
          },

          {
            name: T("电话提醒"),
            type: "phone",
          },
        ],
        selAlertTypes: [],
        //备注
        note: "",
      };
    },

    created() {
      this.pageRef = jnavigator.getParam("pageRef");
      this.id = jnavigator.getParam("id");
      this.indicatorId = jnavigator.getParam("indicatorId");
      weexFunction.setTitle(T("价格提醒"));
      let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
      if (!isIos) {
        this.alertTypes = [
          {
            name: T("Telegram提醒"),
            type: "tg",
          },
          {
            name: T("电话提醒"),
            type: "phone",
          },
        ];
      }
    },

    mounted() {
      this.frequency = this.frequencyList[0];
      this.curDate = this.getCurrentFormattedDate();
      this.httpLoadData();
    },

    methods: {
      /********************************** HTTPS*/
      httpLoadData() {
        if (this.pageRef == "edit") {
          jmodal.showLoad();
          var param = {
            indicatorId: parseInt(this.indicatorId),
          };
          jhttps.post("indicator/getIndicatorInfoById", param, true, (data) => {
            if (data.status == 200) {
              this.updateEditInfo(data.data);
            } else {
              jmodal.hideLoad();
              jmodal.toast(data.msg);
            }
          });
        } else if (this.pageRef == "create") {
          jmodal.showLoad();
          var param = {
            indicatorType: this.type,
          };
          jhttps.post("indicator/getIndicatorInfoList", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              if (data.data.length > 0) {
                this.httpPriceByCreate(data.data[0]);
              }
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jmodal.toast(T("失败"));
          setTimeout(() => {
            jnavigator.back();
          }, 1000);
        }
      },
      //用户编辑信息
      updateEditInfo(editInfo) {
        var param = {
          id: parseInt(this.id),
        };
        jhttps.post("indicator/getUserIndicatorById", param, true, (data) => {
          jmodal.hideLoad();
          if (data.status == 200) {
            this.httpPriceByEdit(editInfo, data.data);
          } else {
            jmodal.toast(data.msg);
          }
        });
      },

      //获取当前价格
      httpPriceData(item) {
        let param = {
          baseCoinShort: item.baseCoinShort || "",
          counterCoinShort: item.counterCoinShort || "",
          exchangeName: item.exchangeName || "",
        };
        jmodal.showLoad();
        jhttps.post("indicator/getPrice", param, true, (data) => {
          jmodal.hideLoad();
          if (data.status == 200) {
            this.curPriceData = null;
            setTimeout(() => {
              this.curPriceData = data.data;
              this.curPriceCondition.oldPrice = this.curPriceData.last;
            }, 10);
          } else {
            jmodal.toast(data.msg);
          }
        });
      },

      httpPriceByCreate(dataInfo) {
        let param = {
          baseCoinShort: "USDT",
          counterCoinShort: "BTC",
          exchangeName: "BINANCE",
        };

        jhttps.post("indicator/getPrice", param, true, (data) => {
          jmodal.hideLoad();
          if (data.status == 200) {
            //当前价格
            this.curPriceData = data.data;
            this.curData = dataInfo;
            this.pair = "BTCUSDT";
            if (this.curData.triggerCondition.hasOwnProperty("price")) {
              this.priceConditionList = this.curData.triggerCondition["price"];
              this.curPriceCondition = this.priceConditionList[0];
            }
          } else {
            jmodal.toast(data.msg);
          }
        });
      },
      httpPriceByEdit(editInfo, userInfo) {
        let param = {
          baseCoinShort: userInfo.baseCoin || "",
          counterCoinShort: userInfo.counterCoin || "",
          exchangeName: userInfo.exchangeName || "",
        };
        jhttps.post("indicator/getPrice", param, true, (data) => {
          jmodal.hideLoad();
          if (data.status == 200) {
            this.curData = editInfo;
            //标的
            this.pair = userInfo.pair || "";
            //当前价格
            this.curPriceData = data.data;
            //价格条件
            if (this.curData.triggerCondition.hasOwnProperty("price")) {
              this.priceConditionList = this.curData.triggerCondition["price"];
            }
            if (userInfo.triggerCondition.hasOwnProperty("price")) {
              this.curPriceCondition = userInfo.triggerCondition["price"];
            }
            //预警频率
            if (userInfo.frequency) {
              this.frequency = this.frequencyList.find(
                (item) => item.type == userInfo.frequency
              );
            }
            //到期时间
            if (userInfo.expirationTime) {
              this.expirationTime = jtime.getTime(
                userInfo.expirationTime,
                "y-M-d H:m:s"
              );
            }
            //预警方式
            this.selAlertTypes = [];
            if (userInfo.appNotification) {
              this.selAlertTypes.push(this.alertTypes[0].type);
            }
            if (userInfo.tgNotification) {
              this.selAlertTypes.push(this.alertTypes[1].type);
            }
            if (userInfo.phNotification) {
              this.selAlertTypes.push(this.alertTypes[2].type);
            }
            this.curPriceCondition.oldPrice = this.curPriceData.last;
            //备注
            this.note = userInfo.remark || "";
          } else {
            jmodal.toast(data.msg);
          }
        });
      },
      /********************************** 点击*/
      //选择标的
      searchClick() {
        this.blur();
        if (this.pageRef == "edit") {
          return;
        }
        this.showPair = true;
      },
      onPairSel(item) {
        if (this.pair != item.pair) {
          this.pair = item.pair;
          this.httpPriceData(item);
        }
      },

      pairHide() {
        setTimeout(() => {
          this.showPair = false;
        }, 200);
      },
      //条件点击
      onConditionClick(data) {
        this.blur();
        if (data.type == "yjFrequency") {
          //切换频率
          let names = [];
          for (let i = 0; i < this.frequencyList.length; i++) {
            let item = this.frequencyList[i];
            names.push(item.name);
          }
          jmodal.actionSheet(names, this.frequency.name, (value) => {
            let index = names.indexOf(value);
            this.frequency = this.frequencyList[index];
          });
        } else if (data.type == "pickerTime") {
          //时间选择器
          this.showPicker = true;
        }
      },

      /********************************** 价格相关*/
      onPriceSel() {
        this.blur();
        let names = [];
        for (let i = 0; i < this.priceConditionList.length; i++) {
          let item = this.priceConditionList[i];
          names.push(T(item.operatorName));
        }
        jmodal.actionSheet(
          names,
          T(this.curPriceCondition.operatorName),
          (value) => {
            let index = names.indexOf(value);
            this.curPriceCondition = this.priceConditionList[index];
            this.curPriceCondition.oldPrice = this.curPriceData.last;
          }
        );
      },
      onPriceChange(price) {
        this.curPriceCondition.value = price;
      },
      onPriceChangeValue1(price) {
        this.curPriceCondition.value1 = price;
      },
      onPriceChangeValue2(price) {
        this.curPriceCondition.value2 = price;
      },
      /********************************** 时间选择器*/
      //时间选择器隐藏
      timePickerHide() {
        setTimeout(() => {
          this.showPicker = false;
        }, 200);
      },
      //时间选择器结果
      timePickerResult(dateTime) {
        this.expirationTime = dateTime;
      },

      /********************************** 预警方式*/
      onAlertTypeSel(item) {
        this.blur();
        let index = this.selAlertTypes.indexOf(item.type);
        if (index == -1) {
          this.selAlertTypes.push(item.type);
        } else {
          this.selAlertTypes.splice(index, 1);
        }
      },
      /********************************** 最终保存*/

      onSave() {
        this.blur();
        // //触发条件
        if (this.pair.length <= 0) {
          jmodal.toast(T("请选择标的"));
          return;
        }
        if (this.curPriceCondition.operator == "up") {
          if (
            Number(this.curPriceCondition.value) < Number(this.curPriceData.last)
          ) {
            jmodal.toast(T("输入价格不能小于当前价格"));
            return;
          }
        } else if (this.curPriceCondition.operator == "down") {
          if (
            Number(this.curPriceCondition.value) > Number(this.curPriceData.last)
          ) {
            jmodal.toast(T("输入价格不能大于当前价格"));
            return;
          }
        } else if (
          this.curPriceCondition.operator == "enteringChannel" ||
          this.curPriceCondition.operator == "exitingChannel"
        ) {
          jdebug.log(this.curPriceCondition.value1);
          jdebug.log(this.curPriceCondition.value2);
          if (
            Number(this.curPriceCondition.value1) <
            Number(this.curPriceCondition.value2)
          ) {
            jmodal.toast(T("上限价格不能小于下限价格"));
            return;
          }
        }
        if (!this.expirationTime || this.expirationTime.length <= 0) {
          jmodal.toast(T("请选择到期时间"));
          return;
        }
        jmodal.showLoad();
        const date = dateUtils.createDate(this.expirationTime);
        let param = {
          indicatorId: parseInt(this.curData.id),
          pair: this.pair,
          frequency: this.frequency.type,
          expirationTime: date.getTime(),
        };
        //价格条件
        param.triggerCondition = JSON.stringify({
          price: this.curPriceCondition,
        });

        //预警方式
        if (this.selAlertTypes.includes("app")) {
          param.appNotification = true;
        } else {
          param.appNotification = false;
        }
        if (this.selAlertTypes.includes("tg")) {
          param.tgNotification = true;
        } else {
          param.tgNotification = false;
        }
        if (this.selAlertTypes.includes("phone")) {
          param.phNotification = true;
        } else {
          param.phNotification = false;
        }
        if (this.note && this.note.length > 0) {
          param.remark = this.note;
        }
        if (this.pageRef == "edit") {
          param.id = parseInt(this.id);
          jhttps.postX("indicator/updateUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jbroadcast.send("IndicatorEdit");
              jnavigator.back();
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jhttps.postX("indicator/createUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jnavigator.back();
              jnavigator.open("", "aide/tipAll", { index: 0 });
            } else {
              jmodal.toast(data.msg);
            }
          });
        }
      },

      /******************************* 其他 */
      //获取当前时间
      //格式化为 YYYY-MM-DD HH:mm:ss
      getCurrentFormattedDate() {
        const now = new Date();
        const year = now.getFullYear(); // 获取年份
        const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 获取月份（0-11），并补零
        const day = now.getDate().toString().padStart(2, "0"); // 获取日期，并补零
        const hours = now.getHours().toString().padStart(2, "0"); // 获取小时，并补零
        const minutes = now.getMinutes().toString().padStart(2, "0"); // 获取分钟，并补零
        const seconds = now.getSeconds().toString().padStart(2, "0"); // 获取秒数，并补零
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      blur() {
        this.$refs.priceUp && this.$refs.priceUp.blur();
        this.$refs.priceDown && this.$refs.priceDown.blur();
        this.$refs.priceEnter && this.$refs.priceEnter.blur();
        this.$refs.priceExit && this.$refs.priceExit.blur();
        this.$refs.note && this.$refs.note.blur();
      },
    },
  };
</script>